const Router = require('koa-router');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const db = require('../db');

const router = new Router();
const SECRET_KEY = 'your_secret_key';

// 注册接口
router.post('/register', async (ctx) => {
    const { username, password } = ctx.request.body;
    const hashedPassword = await bcrypt.hash(password, 10);
    try {
        await db.run("INSERT INTO users (username, password) VALUES (?, ?)", [username, hashedPassword]);
        ctx.body = { message: "注册成功" };
    } catch (error) {
        ctx.status = 500;
        ctx.body = { error: "用户名已存在或其他错误" };
    }
});

// 登录接口
router.post('/login', async (ctx) => {
    const { username, password } = ctx.request.body;
    db.get("SELECT * FROM users WHERE username = ?", [username], async (err, user) => {
        if (err || !user || !(await bcrypt.compare(password, user.password))) {
            ctx.status = 401;
            ctx.body = { error: "用户名或密码错误" };
            return;
        }
        const token = jwt.sign({ id: user.id }, SECRET_KEY, { expiresIn: '1h' });
        ctx.body = { token };
    });
});

module.exports = router;
